Skip to content

feat(bot): scheduled weekly mod digest - #497

Merged
LucasSantana-Dev merged 3 commits into
mainfrom
feat/mod-digest-scheduler
Apr 7, 2026
Merged

LucasSantana-Dev merged 3 commits into
mainfrom
feat/mod-digest-scheduler

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the last S-complexity item from `docs/BOT_COMMAND_ROADMAP_BENCHMARKS.md`: an opt-in weekly automated moderation digest posted to a configurable channel per guild.

  • New `ModDigestConfigService` stores per-guild config in Redis (`mod-digest:config:`) with a Set index of enabled guilds.
  • New `ModDigestSchedulerService` ticks once per hour (configurable via `MOD_DIGEST_TICK_INTERVAL_MS`) and posts the existing `/digest` embed for each due guild based on `lastSentAt + MOD_DIGEST_PERIOD_DAYS`.
  • Embed building extracted into `utils/moderation/digestEmbed.ts` so both the slash command and the scheduler share one builder.
  • `/digest` is now subcommand-based: `view` (default), `schedule`, `unschedule`. Scheduling immediately posts a sample digest in the chosen channel.
  • Scheduler is started inside the existing `client.once('ready')` wiring in `clientHandler/service.ts`.

Tests

  • 32 new tests across `digestEmbed`, `modDigestConfig`, `modDigestScheduler`
  • `digest.spec.ts` rewritten to cover all three subcommands and their error paths
  • Full bot suite: 1497 tests passing

Test plan

  • `npx jest src/utils/moderation src/functions/moderation/commands/digest.spec.ts src/handlers/clientHandler` green
  • `tsc --noEmit` clean
  • `npm run lint` clean
  • Manual: `/digest schedule channel:#mod-log` posts a sample digest immediately
  • Manual: bot restart does not double-post the same week
  • Manual: `/digest unschedule` removes the schedule and `/digest view` still works

Summary by CodeRabbit

  • New Features

    • /digest now has subcommands: view (period option), schedule (enable digests to a text channel), unschedule (disable)
    • Automatic digest scheduler that sends periodic moderation summaries to configured channels
  • Improvements

    • Better user-facing error messages and channel validation when scheduling
  • Tests

    • Expanded test coverage for digest flows, scheduler, config handling, and embed generation

@vercel

vercel Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Apr 7, 2026 10:19pm

Request Review

@github-actions github-actions Bot added the bot label Apr 7, 2026
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 6 minutes and 7 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 6 minutes and 7 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d3a7c8d1-55a2-4c7b-9581-eaccce1bf467

📥 Commits

Reviewing files that changed from the base of the PR and between 3c282c7 and a01c188.

📒 Files selected for processing (6)
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • prisma/migrations/20260407000000_add_moderation_cases_guild_created_at_index/migration.sql
  • prisma/schema.prisma
📝 Walkthrough

Walkthrough

Introduces a subcommand-based /digest (view/schedule/unschedule), embed building utilities, Redis-backed digest config service, a scheduler that periodically sends digests, scheduler startup in the client ready handler, and comprehensive tests for these components.

Changes

Cohort / File(s) Summary
Digest command
packages/bot/src/functions/moderation/commands/digest.ts, packages/bot/src/functions/moderation/commands/digest.spec.ts
Rewrote /digest to use view, schedule, unschedule subcommands. view uses new utilities; schedule validates text channel, sends sample digest then enables config; unschedule disables config. Expanded tests for all flows and error handling.
Embed utilities
packages/bot/src/utils/moderation/digestEmbed.ts, packages/bot/src/utils/moderation/digestEmbed.spec.ts
New typed utilities: resolveDigestPeriodDays, filterCasesSince, buildDigestEmbed and related types. Builds Discord embeds with period-scoped counts and top moderators. Tests validate mapping, filtering, formatting, and pluralization.
Config service
packages/bot/src/utils/moderation/modDigestConfig.ts, packages/bot/src/utils/moderation/modDigestConfig.spec.ts
New ModDigestConfigService persisting per-guild config in Redis plus an enabled-guilds set. Exposes enable, disable, get, listEnabledGuildIds, markSent. Tests cover JSON parsing, enable/disable cycles, and edge cases.
Scheduler service
packages/bot/src/utils/moderation/modDigestScheduler.ts, packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
New ModDigestSchedulerService with start, stop, tick, isDue, sendDigestForGuild. Periodically lists enabled guilds, checks due status, builds/sends embeds, and marks sent. Per-guild error isolation and configurable options. Tests exercise scheduling and failure modes.
Client ready integration
packages/bot/src/handlers/clientHandler/service.ts, packages/bot/src/handlers/clientHandler/service.spec.ts
Starts modDigestSchedulerService from client ready handler (isolated try/catch). Tests add scheduler mock and assert start is invoked, even if earlier ready steps fail.
Moderation data API
packages/shared/src/services/ModerationService.ts
Added getCasesSince(guildId, since) to fetch moderation cases since a timestamp (used by scheduler and view).

Sequence Diagram

sequenceDiagram
    participant Client as Discord Client
    participant Handler as ClientHandler
    participant Scheduler as ModDigestSchedulerService
    participant Config as ModDigestConfigService
    participant Moderation as ModerationService
    participant Channel as Discord Channel

    Client->>Handler: ready event
    Handler->>Scheduler: start(client)
    Scheduler->>Scheduler: begin tick loop (setInterval)

    loop every tick
        Scheduler->>Config: listEnabledGuildIds()
        Config-->>Scheduler: guildIds[]
        loop for each guildId
            Scheduler->>Config: get(guildId)
            Config-->>Scheduler: config
            alt config exists & isDue
                Scheduler->>Moderation: getStats(guildId)
                Moderation-->>Scheduler: stats
                Scheduler->>Moderation: getCasesSince(guildId, since)
                Moderation-->>Scheduler: cases
                Scheduler->>Client: guild.channels.fetch(channelId)
                Client-->>Scheduler: channel
                Scheduler->>Scheduler: buildDigestEmbed(stats, cases)
                Scheduler->>Channel: send(embed)
                Channel-->>Scheduler: success
                Scheduler->>Config: markSent(guildId, now)
            else not due or missing config
                Scheduler-->>Scheduler: skip
            end
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Suggested labels

shared, backend, enhancement

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(bot): scheduled weekly mod digest' clearly and concisely summarizes the main feature addition: implementing scheduled weekly moderation digest functionality for Discord bots.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/mod-digest-scheduler

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot]
coderabbitai Bot previously requested changes Apr 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Nitpick comments (1)
packages/bot/src/functions/moderation/commands/digest.ts (1)

105-110: Route these command failures through the shared error helper.

These catch blocks duplicate literal reply text instead of going through the bot's standard createUserFriendlyError flow, so message consistency and future error metadata will drift across subcommands. Centralizing this would also remove the repeated hard-coded failure strings.

As per coding guidelines, "Use interactionReply and createUserFriendlyError utilities from @lucky/shared/general utils for command replies and error handling".

Also applies to: 153-160, 184-190

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/functions/moderation/commands/digest.ts` around lines 105 -
110, The catch blocks currently call errorLog and then send a hard-coded reply
via interactionReply; replace that pattern with the shared helper by calling
createUserFriendlyError(...) to build the error payload and pass that into
interactionReply, while still logging the original error via errorLog({ message:
'Failed to generate mod digest', error }) (or the corresponding message for the
other catch blocks). Locate the catch handlers that reference errorLog and
interactionReply (e.g., the block around errorLog({ message: 'Failed to generate
mod digest', error: error as Error }) ) and change the reply to await
interactionReply({ interaction, content: createUserFriendlyError(error) }) so
all command failures use the standard createUserFriendlyError flow; apply the
same change to the other two catch blocks mentioned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bot/src/functions/moderation/commands/digest.spec.ts`:
- Around line 119-128: The test currently only checks embed count so it would
pass for any default window; update the fixture to validate the 7-day boundary
by either (A) creating two cases via makeCase with explicit timestamps one at 6
days old and one at 8 days old and assert digestCommand.execute (called via
createInteraction) returns an embed containing only the 6-day case
(interactionReplyMock -> replyArg.content.embeds length 1 and that embed
references the expected case), or (B) assert the returned embed explicitly
mentions the period (e.g., contains "7d" or "7 days") so the test verifies the
default period, using getRecentCasesMock and interactionReplyMock to inspect the
embed content after digestCommand.execute. Ensure you update the makeCase usage
to accept/produce the createdAt timestamp for the boundary ages and keep
references to digestCommand.execute, createInteraction, getRecentCasesMock,
makeCase, and interactionReplyMock when locating code to change.
- Around line 50-58: The test helper createInteraction currently uses nullish
coalescing for subcommand (overrides.subcommand ?? 'view'), which turns an
explicit null into 'view' and prevents exercising the handler's
missing-subcommand fallback; change createInteraction so it only supplies the
'view' default when the subcommand key is absent (e.g., check for hasOwnProperty
or undefined) so a passed null still produces a mock that makes getSubcommand()
return null and triggers the command fallback logic; update the failing test
that intends to exercise the fallback to pass subcommand: null and assert that
the code path that handles a missing subcommand runs (refer to
InteractionOverrides, createInteraction, and getSubcommand()). Also extend the
"defaults to 7d period" test to assert the period argument or expected embed
content (not just embed count) so the hardcoded 7d default is explicitly
verified.

In `@packages/bot/src/functions/moderation/commands/digest.ts`:
- Around line 129-136: The enable flow makes the guild eligible for scheduled
picks before lastSentAt is recorded, risking duplicate digests; update the
sequence so enable + initial send + markSent are atomic: either (A) defer
calling modDigestConfigService.enable(guildId, channelId) until after
modDigestSchedulerService.sendDigestForGuild(...) succeeds and
modDigestConfigService.markSent(guildId) completes, or (B) if you must call
enable first, wrap the try block to catch any error from
modDigestSchedulerService.sendDigestForGuild or modDigestConfigService.markSent
and call modDigestConfigService.disable(guildId, channelId) (or otherwise
rollback the enable) before rethrowing; apply the same fix to the second
enable/send/markSent block that mirrors this flow.

In `@packages/bot/src/handlers/clientHandler/service.spec.ts`:
- Around line 30-35: Tests currently mock modDigestSchedulerService but do not
assert it gets invoked; update the ready-path test that exercises startClient to
assert modDigestSchedulerService.start was called with the client instance
(e.g., expect(modDigestSchedulerService.start).toHaveBeenCalledWith(client)),
ensuring the test imports or references the same mocked
modDigestSchedulerService and uses the client returned/passed by startClient;
also consider verifying stop isn't called on startup if relevant.

In `@packages/bot/src/handlers/clientHandler/service.ts`:
- Around line 80-84: The scheduled digest startup
(modDigestSchedulerService.start) must not be suppressed by failures in the
ready-handler work; move the call out of the main try block and run it in its
own guarded step (either call modDigestSchedulerService.start(client) before
awaiting startTwitchService() and command registration, or place it in a
separate try/catch after the main try) so any errors from startTwitchService()
or command registration do not prevent the scheduler from starting; ensure the
new guarded step logs errors from modDigestSchedulerService.start without
throwing so the process can continue.

In `@packages/bot/src/utils/moderation/modDigestConfig.ts`:
- Around line 20-40: The enable/disable/markSent flows (functions enable,
disable, markSent) perform separate read/write/delete operations against the
same Redis blob and INDEX_KEY, causing lost updates and out-of-sync state under
races; replace these with atomic Redis operations (use a single EVAL Lua script
or a MULTI/EXEC transaction) that: read the existing config key
(getConfigKey(guildId)), compute the new JSON blob (update channelId, enabled,
lastSentAt, createdAt as needed) or delete it, and simultaneously add/remove
guildId from INDEX_KEY in the same atomic call via redisClient; ensure the Lua
script returns the final blob or success flag so callers get consistent results
and handle partial-failure cases accordingly.
- Around line 44-48: The get method currently parses cached JSON blindly
(JSON.parse(raw) as ModDigestConfig) which can produce invalid ModDigestConfig
objects; update the get(guildId: string) implementation to parse raw, then
validate required fields and their types for ModDigestConfig (e.g., check
presence and types of each expected property) after
redisClient.get(this.getConfigKey(guildId)); if validation fails, return null
(or clear the key) instead of casting and returning a malformed object. Use the
get method, ModDigestConfig type, redisClient.get, and getConfigKey to locate
where to add these runtime checks; prefer a small helper or schema validator to
keep the logic readable.

In `@packages/bot/src/utils/moderation/modDigestScheduler.ts`:
- Around line 113-121: The digest currently uses
moderationService.getRecentCases(guildId, this.recentCaseLimit) which caps at
recentCaseLimit (500) and falsely treats that slice as the full period; change
the logic in modDigestScheduler.ts to fetch by cutoff date instead of a fixed
limit: compute cutoff = now - this.periodDays, then either call a new service
method like moderationService.getCasesSince(guildId, cutoff) (implement on
ModerationService to query by createdAt >= cutoff) or implement paging using
moderationService.getRecentCases(guildId, limit, offset) and loop/append pages
until the oldest fetched case is older than cutoff, then pass the full set to
buildDigestEmbed({ stats, cases: recentCases, days: this.periodDays }) so the
digest and top-moderator calculations use the complete window.
- Around line 77-87: The loop that processes guilds should isolate failures per
guild so one error (like modDigestConfigService.markSent throwing) doesn't abort
the whole tick; update the logic around sendDigestForGuild and
modDigestConfigService.markSent so each guild's work is wrapped in its own
try/catch: call sendDigestForGuild(guildId, config.channelId), and if it returns
true attempt to markSent(guildId, this.clock()) inside a nested try/catch that
logs the error (but does not rethrow) and still continues to the next guild;
also wrap the entire per-guild sequence (getting config, checking isDue,
sending, marking) in a try/catch to guard against unexpected errors so
subsequent guilds are processed.
- Around line 49-59: The tick() method is currently reentrant and can cause
duplicate digests; add a private boolean inProgress (or a small queue) on
ModDigestScheduler to return immediately if a tick is already running (set
inProgress = true at the start of tick() and clear it at the end, ensuring
finally semantics) so concurrent interval triggers serialize; update start() to
still schedule the interval but rely on the inProgress guard. Also wrap the call
to markSent() inside tick() with a try-catch so a Redis/update failure for one
guild does not abort processing of remaining guilds (log the error and
continue). Finally, add a regression unit test that calls tick() twice
concurrently and asserts sendDigestForGuild() is invoked only once for the same
guild.

---

Nitpick comments:
In `@packages/bot/src/functions/moderation/commands/digest.ts`:
- Around line 105-110: The catch blocks currently call errorLog and then send a
hard-coded reply via interactionReply; replace that pattern with the shared
helper by calling createUserFriendlyError(...) to build the error payload and
pass that into interactionReply, while still logging the original error via
errorLog({ message: 'Failed to generate mod digest', error }) (or the
corresponding message for the other catch blocks). Locate the catch handlers
that reference errorLog and interactionReply (e.g., the block around errorLog({
message: 'Failed to generate mod digest', error: error as Error }) ) and change
the reply to await interactionReply({ interaction, content:
createUserFriendlyError(error) }) so all command failures use the standard
createUserFriendlyError flow; apply the same change to the other two catch
blocks mentioned.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 208e10af-2cd4-485b-82fa-4e15bf74d1ba

📥 Commits

Reviewing files that changed from the base of the PR and between 1a5eadf and 1ca4574.

📒 Files selected for processing (10)
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (16)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Never hardcode secrets, IPs, or ports; use .env and docs/ for required configuration variables

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
packages/bot/src/functions/**/commands/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Discord bot commands must be structured in packages/bot/src/functions/<category>/commands/<name>.ts with handlers in <category>/handlers/

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
packages/bot/src/functions/*/commands/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/src/functions/*/commands/**/*.{ts,tsx}: Command model must include data (slash builder), execute, and category properties exported from packages/bot/src/models/Command.ts
Use @discordjs/builders for building the data (SlashCommandBuilder) in command definitions
Command execute function must receive { interaction, client } parameters from CommandExecuteParams type
Use interactionReply and createUserFriendlyError utilities from @lucky/shared/general utils for command replies and error handling
Use existing validators from packages/bot/src/utils/command/ for voice channel, queue, and guild validations in commands

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
🧠 Learnings (29)
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When working on unit tests, Jest ESM mocks, or fixing disabled tests, use the `testing-lucky` skill

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Test behavior, not implementation details

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/music/**/*.ts : Use existing voice/queue/guild validators before manipulating player or queue state

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.spec.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/handlers/player/**/*.{ts,tsx} : Track handling, errors, and lifecycle must be managed through dedicated handlers in `packages/bot/src/handlers/player/` (trackHandlers, errorHandlers, lifecycleHandlers)

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/{services,middleware}/**/*.{ts,tsx} : Implement Discord OAuth for authentication in backend services

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use services from `lucky/shared` (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/{services,middleware}/**/*.{ts,tsx} : Use SessionService in middleware for session handling; keep session and auth logic centralized

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to packages/bot/** : The `bot` package depends on `shared` and contains Discord bot commands and player handlers using Discord.js and Discord Player

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Do not duplicate queue or player state outside Discord Player; use shared services from `lucky/shared` for persistent data like track history and session information

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/{server,index}.{ts,tsx} : Backend entry point is `packages/backend/src/server.ts` which imports from `index.ts`

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/music/commands/**/*.ts : Use `.cursor/skills/music-queue-player/SKILL.md` for play, queue, skip, volume commands and player lifecycle management

Applied to files:

  • packages/bot/src/handlers/clientHandler/service.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to tests/**/*.test.{ts,tsx,js,jsx} : Add integration tests where appropriate

Applied to files:

  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Use Jest for unit and integration tests

Applied to files:

  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/tests/**/*.{ts,tsx} : Organize tests in `packages/backend/tests/` with unit tests under `unit/` and integration tests under `integration/`, following existing patterns with fixtures and setup

Applied to files:

  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Run unit, integration tests, and coverage report in CI quality checks

Applied to files:

  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Use `interactionReply` and `createUserFriendlyError` utilities from `lucky/shared/general` utils for command replies and error handling

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use embed and reply utilities from `lucky/shared` for consistent message formatting and error sanitization across the bot

Applied to files:

  • packages/bot/src/utils/moderation/digestEmbed.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/{general,music,download}/commands/**/*.ts : Use `.cursor/skills/discord-commands/SKILL.md` for implementing slash commands

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Use `discordjs/builders` for building the `data` (SlashCommandBuilder) in command definitions

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/{general,music,download}/commands/**/*.ts : Apply `.cursor/rules/lucky-discord-bot.mdc` rules for Discord bot commands and player implementation

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Command model must include `data` (slash builder), `execute`, and `category` properties exported from `packages/bot/src/models/Command.ts`

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:20:23.892Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-03-09T20:20:23.892Z
Learning: Applies to packages/bot/src/functions/**/commands/*.ts : Discord bot commands must be structured in `packages/bot/src/functions/<category>/commands/<name>.ts` with handlers in `<category>/handlers/`

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When building embeds, custom commands, or auto-messages, use the `management-features` skill

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When adding or changing slash commands, use the `discord-commands` skill

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Organize the Lucky Shared Package with the following directory structure: Config in `packages/shared/src/config/` (environment, constants, feature toggles, YouTube config); Services in `packages/shared/src/services/` (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in `packages/shared/src/types/` (errors, commands, common, discord, music); Utils in `packages/shared/src/utils/` (error handling, retry, embeds, log, monitoring, composables, prismaClient)

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/**/*.ts : Use `lucky/shared` for config and DB/Redis when needed in backend code

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Use Redis client and operations located in `packages/shared/src/services/redis/`; use for cache, sessions, and rate limits as defined by existing keys and types

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.ts

Comment thread packages/bot/src/functions/moderation/commands/digest.spec.ts Outdated
Comment thread packages/bot/src/functions/moderation/commands/digest.spec.ts
Comment thread packages/bot/src/functions/moderation/commands/digest.ts Outdated
Comment thread packages/bot/src/handlers/clientHandler/service.spec.ts
Comment thread packages/bot/src/handlers/clientHandler/service.ts
Comment thread packages/bot/src/utils/moderation/modDigestConfig.ts Outdated
Comment thread packages/bot/src/utils/moderation/modDigestConfig.ts Outdated
Comment thread packages/bot/src/utils/moderation/modDigestScheduler.ts
Comment thread packages/bot/src/utils/moderation/modDigestScheduler.ts Outdated
Comment thread packages/bot/src/utils/moderation/modDigestScheduler.ts Outdated
Adds /digest schedule and /digest unschedule subcommands plus a background
scheduler so guilds can opt into automatic weekly moderation summaries.

- New ModDigestConfigService stores per-guild config in Redis
  (mod-digest:config:<guildId>) with a Set index of enabled guilds.
- New ModDigestSchedulerService ticks once per hour (configurable via
  MOD_DIGEST_TICK_INTERVAL_MS) and posts the existing /digest embed for
  each due guild based on lastSentAt + MOD_DIGEST_PERIOD_DAYS.
- Embed building extracted into utils/moderation/digestEmbed.ts so the
  slash command and the scheduler share one builder.
- /digest is now subcommand-based: view (default), schedule, unschedule.
  Scheduling immediately posts a sample digest in the chosen channel.
- Scheduler is started inside the existing client.once('ready') wiring
  in clientHandler/service.ts.

Tests: 32 new tests across digestEmbed, modDigestConfig, modDigestScheduler
plus an updated digest.spec.ts covering all three subcommands and error
paths.
- Eliminate enable() lost-update by writing config atomically with optional
  lastSentAt instead of read-modify-write.
- Add type guard for Redis JSON payloads in modDigestConfig.get to reject
  malformed/missing fields.
- Restructure /digest schedule to send-then-enable so the scheduler tick
  cannot race the sample digest into a duplicate post.
- Isolate per-guild failures in scheduler tick() so one bad guild cannot
  break the whole batch loop.
- Add ModerationService.getCasesSince and use it in the scheduler so the
  weekly window is bounded by date instead of a 500-case truncation.
- Move scheduler startup outside the main ready-handler try block so an
  unrelated upstream failure cannot suppress weekly digests for the entire
  process; cover the new behavior with two new clientHandler tests.
- Use createUserFriendlyError for all /digest catch responses instead of
  hard-coded strings.
- Strengthen the "defaults to 7d period" test with cases that straddle the
  boundary so 30d/90d regressions would actually fail.
coderabbitai[bot]
coderabbitai Bot previously requested changes Apr 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (2)
packages/bot/src/functions/moderation/commands/digest.spec.ts (1)

63-65: ⚠️ Potential issue | 🟡 Minor

This helper still hides the missing-subcommand path.

overrides.subcommand ?? 'view' converts an explicit null into 'view', so the fallback test never exercises getSubcommand(false) ?? 'view' in the command.

🧪 Suggested fix
 function createInteraction(overrides: InteractionOverrides = {}) {
-    const subcommand = overrides.subcommand ?? 'view'
+    const subcommand =
+        Object.prototype.hasOwnProperty.call(overrides, 'subcommand')
+            ? overrides.subcommand
+            : 'view'

Based on learnings, "Test behavior, not implementation details".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/functions/moderation/commands/digest.spec.ts` around lines
63 - 65, The test helper createInteraction currently uses nullish coalescing
(overrides.subcommand ?? 'view') which turns an explicit null into 'view' and
prevents exercising the missing-subcommand path; change the fallback to only
apply when subcommand is undefined (e.g., use a conditional that returns
overrides.subcommand if it's present, otherwise 'view') so an explicit null is
preserved and the code path that calls getSubcommand(false) ?? 'view' can be
tested; update the createInteraction helper accordingly (referencing the
createInteraction function and the subcommand variable).
packages/bot/src/utils/moderation/modDigestScheduler.ts (1)

66-95: ⚠️ Potential issue | 🔴 Critical

Serialize tick() executions to prevent duplicate digests.

Overlapping ticks can both read the same lastSentAt, both send the digest, and only then call markSent(). Add an in-progress guard around the whole method and a regression test that fires two concurrent tick() calls.

🛡️ Suggested guard
 export class ModDigestSchedulerService {
+    private tickInProgress = false
+
     async tick(): Promise<number> {
+        if (this.tickInProgress) return 0
+        this.tickInProgress = true
+        try {
             if (!this.client) return 0

             const guildIds = await modDigestConfigService.listEnabledGuildIds()
             if (guildIds.length === 0) return 0
@@
             }
             return sent
+        } finally {
+            this.tickInProgress = false
+        }
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/utils/moderation/modDigestScheduler.ts` around lines 66 -
95, tick() can run concurrently causing duplicate digests; add a guard boolean
(e.g., this.tickInProgress) on the ModDigestScheduler class to serialize
executions: at the start of tick() return 0 if the guard is set, set the guard
before work begins and clear it in a finally block so it always resets even on
errors; keep existing behavior for early returns (this.client check and empty
guildIds). Also add a regression test that calls tick() twice concurrently and
asserts only one digest is sent (verify modDigestConfigService.markSent or sent
count).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bot/src/functions/moderation/commands/digest.ts`:
- Around line 94-101: Replace the newest-500 approach in the /digest view with
the cutoff-based query: compute the cutoff (based on the days param) and call
moderationService.getCasesSince(guildId, cutoff) instead of
moderationService.getRecentCases(guildId, VIEW_RECENT_CASE_LIMIT), then pass the
returned cases into buildDigestEmbed({ stats, cases: recentCases, days }) so the
view receives the same cutoff-shaped data as the scheduler; keep
moderationService.getStats(guildId) as-is.

In `@packages/bot/src/utils/moderation/modDigestScheduler.ts`:
- Around line 28-43: The constructor currently assigns tickIntervalMs and
periodDays from env vars using parseInt without validation; update the
constructor (references: ModDigestSchedulerOptions constructor, tickIntervalMs,
periodDays, MOD_DIGEST_TICK_INTERVAL_MS, MOD_DIGEST_PERIOD_DAYS,
DEFAULT_TICK_INTERVAL_MS, DEFAULT_PERIOD_DAYS) to validate parsed values up
front: parse each env value, check for NaN or non-positive numbers, and if
invalid either fallback to the corresponding DEFAULT_* constant or throw a clear
error (choose fallback behavior consistent with project policy); ensure the
validated numeric value is then assigned to this.tickIntervalMs and
this.periodDays so downstream timer setup and window math never receive invalid
values.

In `@packages/shared/src/services/ModerationService.ts`:
- Around line 128-136: The getCasesSince method queries ModerationCase by
guildId and createdAt but the Prisma schema only has @@index([guildId]); update
the model ModerationCase in prisma/schema.prisma to add a composite index
@@index([guildId, createdAt]) so the query can use an index; after updating the
schema run the appropriate Prisma migration (prisma migrate dev/migrate deploy)
and regenerate the Prisma client so the change takes effect for the
getCasesSince function.

---

Duplicate comments:
In `@packages/bot/src/functions/moderation/commands/digest.spec.ts`:
- Around line 63-65: The test helper createInteraction currently uses nullish
coalescing (overrides.subcommand ?? 'view') which turns an explicit null into
'view' and prevents exercising the missing-subcommand path; change the fallback
to only apply when subcommand is undefined (e.g., use a conditional that returns
overrides.subcommand if it's present, otherwise 'view') so an explicit null is
preserved and the code path that calls getSubcommand(false) ?? 'view' can be
tested; update the createInteraction helper accordingly (referencing the
createInteraction function and the subcommand variable).

In `@packages/bot/src/utils/moderation/modDigestScheduler.ts`:
- Around line 66-95: tick() can run concurrently causing duplicate digests; add
a guard boolean (e.g., this.tickInProgress) on the ModDigestScheduler class to
serialize executions: at the start of tick() return 0 if the guard is set, set
the guard before work begins and clear it in a finally block so it always resets
even on errors; keep existing behavior for early returns (this.client check and
empty guildIds). Also add a regression test that calls tick() twice concurrently
and asserts only one digest is sent (verify modDigestConfigService.markSent or
sent count).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: eae81f1d-9b46-485c-95ab-e6574efc565f

📥 Commits

Reviewing files that changed from the base of the PR and between 1ca4574 and 3c282c7.

📒 Files selected for processing (11)
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
  • packages/shared/src/services/ModerationService.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/bot/src/utils/moderation/modDigestScheduler.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/bot/src/handlers/clientHandler/service.ts
  • packages/bot/src/handlers/clientHandler/service.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.spec.ts
  • packages/bot/src/utils/moderation/digestEmbed.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (20)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/shared/src/services/ModerationService.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/shared/src/services/ModerationService.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/shared/src/services/ModerationService.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/shared/src/services/ModerationService.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Never hardcode secrets, IPs, or ports; use .env and docs/ for required configuration variables

Files:

  • packages/shared/src/services/ModerationService.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/shared/src/services/ModerationService.ts
  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
{packages/shared/**,prisma/**}/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Files:

  • packages/shared/src/services/ModerationService.ts
packages/shared/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/lucky-shared.mdc)

packages/shared/**/*.ts: Organize the Lucky Shared Package with the following directory structure: Config in packages/shared/src/config/ (environment, constants, feature toggles, YouTube config); Services in packages/shared/src/services/ (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in packages/shared/src/types/ (errors, commands, common, discord, music); Utils in packages/shared/src/utils/ (error handling, retry, embeds, log, monitoring, composables, prismaClient)
Do not add dependencies on bot or backend packages; shared is the foundational package used by both
Use the single Prisma client located at packages/shared/src/utils/database/prismaClient.ts; maintain schema in repo root at prisma/schema.prisma; run migrations from root using npm run db:migrate
Use Redis client and operations located in packages/shared/src/services/redis/; use for cache, sessions, and rate limits as defined by existing keys and types
Use typed errors from packages/shared/src/types/errors/ for domain failures; avoid using generic Error for application-specific failures
Use shared log and monitoring utils for logging and monitoring in production code paths; do not use direct console statements for production logging

Files:

  • packages/shared/src/services/ModerationService.ts
packages/shared/**/*

📄 CodeRabbit inference engine (.cursor/rules/subagent-data.mdc)

Shared client and services must be located in packages/shared

Files:

  • packages/shared/src/services/ModerationService.ts
**/[A-Z]*.{ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

Components must use PascalCase naming

Files:

  • packages/shared/src/services/ModerationService.ts
packages/bot/src/functions/**/commands/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Discord bot commands must be structured in packages/bot/src/functions/<category>/commands/<name>.ts with handlers in <category>/handlers/

Files:

  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
packages/bot/src/functions/*/commands/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/src/functions/*/commands/**/*.{ts,tsx}: Command model must include data (slash builder), execute, and category properties exported from packages/bot/src/models/Command.ts
Use @discordjs/builders for building the data (SlashCommandBuilder) in command definitions
Command execute function must receive { interaction, client } parameters from CommandExecuteParams type
Use interactionReply and createUserFriendlyError utilities from @lucky/shared/general utils for command replies and error handling
Use existing validators from packages/bot/src/utils/command/ for voice channel, queue, and guild validations in commands

Files:

  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
  • packages/bot/src/utils/moderation/modDigestScheduler.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
🧠 Learnings (16)
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Use `discordjs/builders` for building the `data` (SlashCommandBuilder) in command definitions

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/{general,music,download}/commands/**/*.ts : Use `.cursor/skills/discord-commands/SKILL.md` for implementing slash commands

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Use `interactionReply` and `createUserFriendlyError` utilities from `lucky/shared/general` utils for command replies and error handling

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
  • packages/bot/src/functions/moderation/commands/digest.spec.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When building embeds, custom commands, or auto-messages, use the `management-features` skill

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Command model must include `data` (slash builder), `execute`, and `category` properties exported from `packages/bot/src/models/Command.ts`

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When adding or changing slash commands, use the `discord-commands` skill

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Test behavior, not implementation details

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Command `execute` function must receive `{ interaction, client }` parameters from `CommandExecuteParams` type

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When working on unit tests, Jest ESM mocks, or fixing disabled tests, use the `testing-lucky` skill

Applied to files:

  • packages/bot/src/functions/moderation/commands/digest.spec.ts
  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to tests/**/*.test.{ts,tsx,js,jsx} : Add integration tests where appropriate

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/tests/**/*.{ts,tsx} : Organize tests in `packages/backend/tests/` with unit tests under `unit/` and integration tests under `integration/`, following existing patterns with fixtures and setup

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Use Jest for unit and integration tests

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use services from `lucky/shared` (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Organize the Lucky Shared Package with the following directory structure: Config in `packages/shared/src/config/` (environment, constants, feature toggles, YouTube config); Services in `packages/shared/src/services/` (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in `packages/shared/src/types/` (errors, commands, common, discord, music); Utils in `packages/shared/src/utils/` (error handling, retry, embeds, log, monitoring, composables, prismaClient)

Applied to files:

  • packages/bot/src/utils/moderation/modDigestConfig.spec.ts

Comment thread packages/bot/src/functions/moderation/commands/digest.ts Outdated
Comment thread packages/bot/src/utils/moderation/modDigestScheduler.ts
Comment thread packages/shared/src/services/ModerationService.ts
@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

CodeRabbit feedback addressed in 3c282c7 (force-pushed up to current HEAD).

Changes:

  • Atomic enable() with optional lastSentAt — eliminates lost-update on parallel /digest schedule
  • Type guard on Redis JSON parse in modDigestConfig.get
  • /digest schedule now sends sample first then enables → no race window for the tick
  • tick() per-guild try/catch — one bad guild can't break the loop
  • ModerationService.getCasesSince + use it in scheduler → no 500-case truncation
  • Scheduler startup moved outside main ready-handler try → can't be suppressed by an unrelated upstream failure
  • All catch blocks use createUserFriendlyError instead of hard-coded strings
  • Strengthened defaults-to-7d test with cases that straddle the 7-day boundary
  • 2 new clientHandler tests asserting scheduler.start runs (happy + upstream-failure paths)

All 1503 bot tests pass, lint clean, tsc clean.

- Serialize tick() with a tickInProgress guard so two overlapping ticks
  cannot both pass the isDue check and double-deliver a digest. Add a
  regression test that fires two concurrent tick() calls and asserts
  exactly one delivery + one markSent.
- Validate MOD_DIGEST_TICK_INTERVAL_MS / MOD_DIGEST_PERIOD_DAYS env values
  via parsePositiveIntEnv: NaN or non-positive parses fall back to the
  default and emit an errorLog instead of poisoning the timer.
- Switch /digest view to moderationService.getCasesSince(cutoff) so the
  command and the scheduler share the same cutoff-shaped query — kills
  the 500-row truncation in the view path.
- Add Prisma composite index moderation_cases_guildId_createdAt_idx so
  the new getCasesSince query is index-served instead of doing a heap
  scan filtered in memory.
- createInteraction test helper now preserves an explicit { subcommand:
  null } so the missing-subcommand fallback (getSubcommand(false) ?? 'view')
  is actually exercised, not silently rewritten to 'view' by ??.
@github-actions github-actions Bot added database and removed backend labels Apr 7, 2026
@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Second CodeRabbit pass addressed in a01c188:

Critical:

  • tick() now serializes via tickInProgress guard. Concurrent ticks short-circuit instead of double-delivering. New regression test fires Promise.all([tick, tick]) and asserts exactly 1 send + 1 markSent.

Major:

  • /digest view switched to getCasesSince(cutoff) — same shape as the scheduler. Kills the 500-row truncation in the view path.
  • Env vars MOD_DIGEST_TICK_INTERVAL_MS / MOD_DIGEST_PERIOD_DAYS validated via parsePositiveIntEnv — NaN/non-positive falls back to defaults with an errorLog.
  • Added Prisma composite index moderation_cases_guildId_createdAt_idx + migration so getCasesSince is index-served.

Minor:

  • createInteraction helper now preserves { subcommand: null } via hasOwnProperty check so the missing-subcommand fallback path is actually exercised.

All 1505 bot tests pass (added 2 new ones), lint clean, tsc clean.

@sonarqubecloud

sonarqubecloud Bot commented Apr 7, 2026

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev dismissed stale reviews from coderabbitai[bot] and coderabbitai[bot] April 7, 2026 22:22

Addressed in 3c282c7

@LucasSantana-Dev
LucasSantana-Dev merged commit f6f067a into main Apr 7, 2026
12 checks passed
@LucasSantana-Dev LucasSantana-Dev mentioned this pull request Apr 7, 2026
3 of 6 tasks
LucasSantana-Dev added a commit that referenced this pull request Apr 7, 2026
- Bump IMPLEMENTATION_STATUS.md header to v2.6.64
- Replace on-demand `/digest` entry with split view/schedule/unschedule
  descriptions so the shipped scheduler (v2.6.64) is visible alongside
  the v2.6.24 view accuracy fix
- Remove "Scheduled mod digest" from Known Gaps — shipped in PR #497/#499
- Archive .agents/plans/lastfm-improvements-2026-03-30.md now that all
  three phases (duration fix, normalizers, top tracks seeds) shipped
  in e1b4af3 and stabilized through v2.6.61
LucasSantana-Dev added a commit that referenced this pull request Apr 7, 2026
Sync IMPLEMENTATION_STATUS.md Known Gaps to reflect v2.6.64:

- Bump header from v2.6.63 to v2.6.64
- Split the single `/digest` bullet into view/schedule/unschedule so
  the shipped scheduler surface is visible alongside the v2.6.24 view
  entry (+ the v2.6.64 view accuracy fix via getCasesSince)
- Drop "Scheduled mod digest" row from Known Gaps — shipped in #497/#499
LucasSantana-Dev added a commit that referenced this pull request Apr 8, 2026
* docs: sync implementation status to v2.6.64, archive shipped lastfm plan

- Bump IMPLEMENTATION_STATUS.md header to v2.6.64
- Replace on-demand `/digest` entry with split view/schedule/unschedule
  descriptions so the shipped scheduler (v2.6.64) is visible alongside
  the v2.6.24 view accuracy fix
- Remove "Scheduled mod digest" from Known Gaps — shipped in PR #497/#499
- Archive .agents/plans/lastfm-improvements-2026-03-30.md now that all
  three phases (duration fix, normalizers, top tracks seeds) shipped
  in e1b4af3 and stabilized through v2.6.61

* docs: remove shipped scheduled mod digest from known gaps

Sync IMPLEMENTATION_STATUS.md Known Gaps to reflect v2.6.64:

- Bump header from v2.6.63 to v2.6.64
- Split the single `/digest` bullet into view/schedule/unschedule so
  the shipped scheduler surface is visible alongside the v2.6.24 view
  entry (+ the v2.6.64 view accuracy fix via getCasesSince)
- Drop "Scheduled mod digest" row from Known Gaps — shipped in #497/#499
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
* feat(bot): scheduled weekly mod digest

Adds /digest schedule and /digest unschedule subcommands plus a background
scheduler so guilds can opt into automatic weekly moderation summaries.

- New ModDigestConfigService stores per-guild config in Redis
  (mod-digest:config:<guildId>) with a Set index of enabled guilds.
- New ModDigestSchedulerService ticks once per hour (configurable via
  MOD_DIGEST_TICK_INTERVAL_MS) and posts the existing /digest embed for
  each due guild based on lastSentAt + MOD_DIGEST_PERIOD_DAYS.
- Embed building extracted into utils/moderation/digestEmbed.ts so the
  slash command and the scheduler share one builder.
- /digest is now subcommand-based: view (default), schedule, unschedule.
  Scheduling immediately posts a sample digest in the chosen channel.
- Scheduler is started inside the existing client.once('ready') wiring
  in clientHandler/service.ts.

Tests: 32 new tests across digestEmbed, modDigestConfig, modDigestScheduler
plus an updated digest.spec.ts covering all three subcommands and error
paths.

* fix(mod-digest): address CodeRabbit review on PR #497

- Eliminate enable() lost-update by writing config atomically with optional
  lastSentAt instead of read-modify-write.
- Add type guard for Redis JSON payloads in modDigestConfig.get to reject
  malformed/missing fields.
- Restructure /digest schedule to send-then-enable so the scheduler tick
  cannot race the sample digest into a duplicate post.
- Isolate per-guild failures in scheduler tick() so one bad guild cannot
  break the whole batch loop.
- Add ModerationService.getCasesSince and use it in the scheduler so the
  weekly window is bounded by date instead of a 500-case truncation.
- Move scheduler startup outside the main ready-handler try block so an
  unrelated upstream failure cannot suppress weekly digests for the entire
  process; cover the new behavior with two new clientHandler tests.
- Use createUserFriendlyError for all /digest catch responses instead of
  hard-coded strings.
- Strengthen the "defaults to 7d period" test with cases that straddle the
  boundary so 30d/90d regressions would actually fail.

* fix(mod-digest): address second CodeRabbit pass on PR #497

- Serialize tick() with a tickInProgress guard so two overlapping ticks
  cannot both pass the isDue check and double-deliver a digest. Add a
  regression test that fires two concurrent tick() calls and asserts
  exactly one delivery + one markSent.
- Validate MOD_DIGEST_TICK_INTERVAL_MS / MOD_DIGEST_PERIOD_DAYS env values
  via parsePositiveIntEnv: NaN or non-positive parses fall back to the
  default and emit an errorLog instead of poisoning the timer.
- Switch /digest view to moderationService.getCasesSince(cutoff) so the
  command and the scheduler share the same cutoff-shaped query — kills
  the 500-row truncation in the view path.
- Add Prisma composite index moderation_cases_guildId_createdAt_idx so
  the new getCasesSince query is index-served instead of doing a heap
  scan filtered in memory.
- createInteraction test helper now preserves an explicit { subcommand:
  null } so the missing-subcommand fallback (getSubcommand(false) ?? 'view')
  is actually exercised, not silently rewritten to 'view' by ??.
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
* docs: sync implementation status to v2.6.64, archive shipped lastfm plan

- Bump IMPLEMENTATION_STATUS.md header to v2.6.64
- Replace on-demand `/digest` entry with split view/schedule/unschedule
  descriptions so the shipped scheduler (v2.6.64) is visible alongside
  the v2.6.24 view accuracy fix
- Remove "Scheduled mod digest" from Known Gaps — shipped in PR #497/#499
- Archive .agents/plans/lastfm-improvements-2026-03-30.md now that all
  three phases (duration fix, normalizers, top tracks seeds) shipped
  in e1b4af3 and stabilized through v2.6.61

* docs: remove shipped scheduled mod digest from known gaps

Sync IMPLEMENTATION_STATUS.md Known Gaps to reflect v2.6.64:

- Bump header from v2.6.63 to v2.6.64
- Split the single `/digest` bullet into view/schedule/unschedule so
  the shipped scheduler surface is visible alongside the v2.6.24 view
  entry (+ the v2.6.64 view accuracy fix via getCasesSince)
- Drop "Scheduled mod digest" row from Known Gaps — shipped in #497/#499
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
* feat(bot): scheduled weekly mod digest

Adds /digest schedule and /digest unschedule subcommands plus a background
scheduler so guilds can opt into automatic weekly moderation summaries.

- New ModDigestConfigService stores per-guild config in Redis
  (mod-digest:config:<guildId>) with a Set index of enabled guilds.
- New ModDigestSchedulerService ticks once per hour (configurable via
  MOD_DIGEST_TICK_INTERVAL_MS) and posts the existing /digest embed for
  each due guild based on lastSentAt + MOD_DIGEST_PERIOD_DAYS.
- Embed building extracted into utils/moderation/digestEmbed.ts so the
  slash command and the scheduler share one builder.
- /digest is now subcommand-based: view (default), schedule, unschedule.
  Scheduling immediately posts a sample digest in the chosen channel.
- Scheduler is started inside the existing client.once('ready') wiring
  in clientHandler/service.ts.

Tests: 32 new tests across digestEmbed, modDigestConfig, modDigestScheduler
plus an updated digest.spec.ts covering all three subcommands and error
paths.

* fix(mod-digest): address CodeRabbit review on PR #497

- Eliminate enable() lost-update by writing config atomically with optional
  lastSentAt instead of read-modify-write.
- Add type guard for Redis JSON payloads in modDigestConfig.get to reject
  malformed/missing fields.
- Restructure /digest schedule to send-then-enable so the scheduler tick
  cannot race the sample digest into a duplicate post.
- Isolate per-guild failures in scheduler tick() so one bad guild cannot
  break the whole batch loop.
- Add ModerationService.getCasesSince and use it in the scheduler so the
  weekly window is bounded by date instead of a 500-case truncation.
- Move scheduler startup outside the main ready-handler try block so an
  unrelated upstream failure cannot suppress weekly digests for the entire
  process; cover the new behavior with two new clientHandler tests.
- Use createUserFriendlyError for all /digest catch responses instead of
  hard-coded strings.
- Strengthen the "defaults to 7d period" test with cases that straddle the
  boundary so 30d/90d regressions would actually fail.

* fix(mod-digest): address second CodeRabbit pass on PR #497

- Serialize tick() with a tickInProgress guard so two overlapping ticks
  cannot both pass the isDue check and double-deliver a digest. Add a
  regression test that fires two concurrent tick() calls and asserts
  exactly one delivery + one markSent.
- Validate MOD_DIGEST_TICK_INTERVAL_MS / MOD_DIGEST_PERIOD_DAYS env values
  via parsePositiveIntEnv: NaN or non-positive parses fall back to the
  default and emit an errorLog instead of poisoning the timer.
- Switch /digest view to moderationService.getCasesSince(cutoff) so the
  command and the scheduler share the same cutoff-shaped query — kills
  the 500-row truncation in the view path.
- Add Prisma composite index moderation_cases_guildId_createdAt_idx so
  the new getCasesSince query is index-served instead of doing a heap
  scan filtered in memory.
- createInteraction test helper now preserves an explicit { subcommand:
  null } so the missing-subcommand fallback (getSubcommand(false) ?? 'view')
  is actually exercised, not silently rewritten to 'view' by ??.
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
* docs: sync implementation status to v2.6.64, archive shipped lastfm plan

- Bump IMPLEMENTATION_STATUS.md header to v2.6.64
- Replace on-demand `/digest` entry with split view/schedule/unschedule
  descriptions so the shipped scheduler (v2.6.64) is visible alongside
  the v2.6.24 view accuracy fix
- Remove "Scheduled mod digest" from Known Gaps — shipped in PR #497/#499
- Archive .agents/plans/lastfm-improvements-2026-03-30.md now that all
  three phases (duration fix, normalizers, top tracks seeds) shipped
  in a17c774 and stabilized through v2.6.61

* docs: remove shipped scheduled mod digest from known gaps

Sync IMPLEMENTATION_STATUS.md Known Gaps to reflect v2.6.64:

- Bump header from v2.6.63 to v2.6.64
- Split the single `/digest` bullet into view/schedule/unschedule so
  the shipped scheduler surface is visible alongside the v2.6.24 view
  entry (+ the v2.6.64 view accuracy fix via getCasesSince)
- Drop "Scheduled mod digest" row from Known Gaps — shipped in #497/#499
@LucasSantana-Dev
LucasSantana-Dev deleted the feat/mod-digest-scheduler branch May 23, 2026 02:21

This branch was successfully deployed

1 active deployment
Preview — a01c1882 Deployed Apr 7, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant